<template>
  <div class="order-container">
    <van-nav-bar title="订单" fixed placeholder />

    <van-tabs v-model:active="activeTab">
      <van-tab title="全部订单"></van-tab>
      <van-tab title="退款记录"></van-tab>
      <van-tab title="平台售后记录"></van-tab>
    </van-tabs>

    <div class="order-list">
      <!-- 订单项 -->
      <van-cell-group inset v-for="order in orders" :key="order.orderId">
        <van-cell :title="order.status" :class="['custom-cell']">
  <template #value>
    <span type="primary" @click="showOrderDetail(order.orderId)" class="detail-link">
      订单详情 >
    </span>
  </template>
</van-cell>

<van-cell v-if="order.status === '已取消'">
    <div style="text-align: left !important; font-size: 12px; color: #999; margin-top: 4px;">
      {{ order.description }}
    </div>
</van-cell>

        <van-cell>
          <template #title>
            <div class="order-info">
              <div>订单编号：{{ order.orderId }}</div>
              <div>服务内容：{{ order.serviceName }}</div>
              <div>创建时间：{{ formatTime(order.createTime) }}</div>
            </div>
          </template>
        </van-cell>

        <van-cell>
          <div class="order-actions" v-if="order.status !== '待支付'">
            <van-button size="mini" plain class="delete-btn" @click="deleteOrder(order.orderId)">
              删除订单
            </van-button>
          </div>
        </van-cell>
      </van-cell-group>

    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import {
  NavBar,
  Tab,
  Tabs,
  Cell,
  CellGroup,
  Button,
  showDialog, // Vant 4.x 函数式API
  showToast,
  showConfirmDialog
} from 'vant';
import { getOrdersByUserWithService, deleteOrderByid, deleteOrderDetailByid } from '@/api/index';
import { useRouter } from 'vue-router'; // 添加这行导入

import { onBeforeMount } from 'vue'
import { useRoute } from 'vue-router'
import { useUserInfoStore } from '../stores/userInfo'
const UserInfoStore = useUserInfoStore()

const route = useRoute()
const uid = ref(1)


// 获取路由实例
const router = useRouter();
const activeTab = ref(0);
const orders = ref([]);
const loading = ref(false);

// 获取当前用户ID（根据你的实际项目调整）
// const currentUserId = ref(1001); // 示例ID，实际应从登录状态获取

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return '无';
  return new Date(timestamp).toLocaleString();
};

// 获取订单列表
const fetchOrders = async () => {
  try {
    loading.value = true;
     if(UserInfoStore.$state.uid !=undefined &&UserInfoStore.$state.uid!=''){
      uid.value=UserInfoStore.$state.uid    
      // console.log(  uid.value);
     
  }
    const res = await getOrdersByUserWithService(uid.value);
    // console.log('res',res);
    orders.value = res;
    // console.log(orders.value);
    if (orders.value.length === 0) {
      error.value = '暂无订单数据';
    }
  } catch (err) {
    console.error('获取订单失败:', err);
    err.value = '加载订单失败，请重试';
    showToast({
      type: 'fail',
      message: '加载失败',
      duration: 1500,
    });
  } finally {
    loading.value = false;
  }
};

// 初始化加载
onMounted(() => {
  fetchOrders();
});

// 跳转到订单详情页
const showOrderDetail = (orderId) => {
  // console.log('跳转传递的orderId:', orderId); // 先确认有值
  router.push({
    name: 'orderDetail', // 使用路由名称导航
    query: { orderId } // 传递订单ID
  });
};

//删除订单
const deleteOrder = (orderId) => {
  showConfirmDialog({
    title: '删除订单',
    message: '确定要删除此订单吗？',
  }).then(async () => {
    try {
      // await deleteOrderDetailByid(orderId)
      // await deleteOrderByid(orderId)
      // 2. 并行删除订单和订单详情（如果接口支持）
      // console.log('orderId', orderId);
      await Promise.all([
        deleteOrderDetailByid(orderId),
        deleteOrderByid(orderId)
      ]);
      // showSuccessToast('删除成功！')
      // 删除成功后刷新订单列表
      fetchOrders();
      showToast({
        type: 'success',
        message: '删除成功',
        duration: 1500,
      });
    } catch (err) {
      console.error('删除订单失败:', err);
      showToast({
        type: 'fail',
        message: '删除失败',
        duration: 1500,
      });
    }
  }).catch(() => {
    // 用户取消删除
  });
};

</script>

<style scoped>
.order-container {
  background-color: #f7f8fa;
  min-height: 100vh;
}

.order-list {
  margin-top: 16px;
}

.order-info {
  font-size: 14px;
  color: #666;
  line-height: 1.6;
}

.order-actions {
  display: flex;
  justify-content: flex-end;
  padding: 8px 0;
  width: 100px;
}

.order-actions .van-button {
  flex: 1;
  margin: 0 4px;
}

.order-status {
  font-size: 18px;
  /* 加大字体 */
  font-weight: bold;
  /* 加粗 */
  color: #333;
  /* 深色更醒目 */
  margin-bottom: 4px;
}

/* 左侧标题样式 */
.custom-cell :deep(.van-cell__title) {
  font-size: 20px;
  font-weight: bold;
}

/* 右侧链接样式 */
.detail-link {
  font-size: 12px;
}

/* 删除按钮样式 */
.delete-btn {
  border-radius: 20px !important;
  height: 30px !important;
  line-height: 30px !important;
  padding: 0 12px !important;
  font-size: 14px !important;
  border-width: 1px !important;
}
</style>